import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.List;

import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;

import cmpe273.classproject.server.dto.MovieResponse;
import cmpe273.classproject.server.dto.PersonResponse;
import cmpe273.classproject.server.model.Movie;
import cmpe273.classproject.server.model.Person;
import cmpe273.classproject.server.model.RentalTransaction;
import cmpe273.classproject.server.service.MovieServiceImplProxy;

public class AllMovies extends javax.swing.JFrame {

    /** Creates new form AllMovies */
    public AllMovies() {
        initComponents();
        List<Movie> movies = getAllMovies();
        loadMovies(movies);
    }
    
    public AllMovies(NewMovie ui) {
    	newMovie = ui;
        initComponents();
        List<Movie> movies = getAllMovies();
        loadMovies(movies);
    }
    
    public AllMovies(SimpleCustomer ui) {
    	simpleCustomer = ui;
        initComponents();
        List<Movie> movies = getAllMovies();
        loadMovies(movies);
    }
    
    public AllMovies(PremiumMemb ui) {
    	premiumMemb = ui;
        initComponents();
        List<Movie> movies = getAllMovies();
        loadMovies(movies);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        grdMovies = new javax.swing.JTable();
        jLabel1 = new javax.swing.JLabel();
        jButton3 = new javax.swing.JButton();
        jButton4 = new javax.swing.JButton();
        jButton6 = new javax.swing.JButton();
        jLabel2 = new javax.swing.JLabel();
        txtName = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        txtBanner = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        txtCategory = new javax.swing.JTextField();
        jLabel5 = new javax.swing.JLabel();
        txtYear = new javax.swing.JTextField();
        jButton5 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.HIDE_ON_CLOSE);

        grdMovies.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null}
            },
            new String [] {
                "S. No.", "Title", "Banner", "Release Date", "Genre", "Rent", "Avail. Copies"
            }
        ));
        jScrollPane1.setViewportView(grdMovies);

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        jLabel1.setText("Movies");

        jButton3.setText("Add New");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        jButton4.setText("Delete");
        jButton4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton4ActionPerformed(evt);
            }
        });

        jButton6.setText("Edit");
        jButton6.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton6ActionPerformed(evt);
            }
        });

        jLabel2.setText("Movie Name:");

        jLabel3.setText("Movie Banner:");

        jLabel4.setText("Category:");

        jLabel5.setText("Release Year:");

        jButton5.setText("Search");
        jButton5.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton5ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel2)
                                .addGap(18, 18, 18)
                                .addComponent(txtName, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                                    .addComponent(jLabel4)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                    .addComponent(txtCategory, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                                    .addComponent(jLabel3)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                    .addComponent(txtBanner, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel5)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(txtYear, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(148, 148, 148)
                                .addComponent(jButton5))
                            .addComponent(jLabel1)))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(152, 152, 152)
                        .addComponent(jButton3)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton4)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton6))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 528, Short.MAX_VALUE)))
                .addContainerGap())
        );

        layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {jButton3, jButton4, jButton6});

        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(txtName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(txtBanner, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel4)
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel5)
                            .addComponent(txtYear, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jButton5)))
                    .addComponent(txtCategory, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addComponent(jLabel1)
                .addGap(18, 18, 18)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 131, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(70, 70, 70)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton6)
                    .addComponent(jButton4)
                    .addComponent(jButton3))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>

    public NewMovie newMovie = null;
    public PremiumMemb premiumMemb = null;
    public SimpleCustomer simpleCustomer = null;
    public int memberId;
    public boolean bIssueMovie = false;
    public boolean bPremium = false;
    
    public void loadControls()
    {
    	if (bIssueMovie)
    	{
    		jButton3.setVisible(false);
    		jButton6.setVisible(false);
    		jButton4.setText("Issue");
    	}
    	else
    	{
    		jButton3.setVisible(true);
    		jButton6.setVisible(true);
    		jButton4.setText("Delete");
    	}
    }
    
    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
        // add new
        
        if (newMovie == null)
            {
                newMovie = new NewMovie(this);
            }
        
        newMovie.bNew = true;
        newMovie.setVisible(true);
        //this.setVisible(false);  
    }

    private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
        // delete
    	
    	if (!bIssueMovie)
    	{
	    	if (grdMovies.getSelectedRow() < 0)
	        {
	            JOptionPane.showMessageDialog(this, "Please select member to view member's details.");
	            return;
	        }    	    
	    	
	    	
			int iSelectedRow = grdMovies.getSelectedRow();
		    int movieId = Integer.parseInt(grdMovies.getValueAt(iSelectedRow, 0).toString());
		    deletePerson(movieId);
	       
		    List<Movie> movies = getAllMovies();
		    
	        loadMovies(movies);
    	}
    	else
    	{
    		if (grdMovies.getSelectedRow() < 0)
	        {
	            JOptionPane.showMessageDialog(this, "Please select movie to issue.");
	            return;
	        }
	    	
	    	int iSelectedRow = grdMovies.getSelectedRow();
	        int movieId = Integer.parseInt(grdMovies.getValueAt(iSelectedRow, 0).toString());
	        
	        issueMovie(memberId, movieId);
	        
    		if(bPremium)
    		{
    			premiumMemb.loadMovies();    			
    		}
    		else
    		{
    			simpleCustomer.loadMovies();    			
    		}
    		
    		this.dispose();
    	}
    }

    private void jButton6ActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
        // edit
    	
    	if (grdMovies.getSelectedRow() < 0)
        {
            JOptionPane.showMessageDialog(this, "Please select member to view member's details.");
            return;
        }
    	
    	int iSelectedRow = grdMovies.getSelectedRow();
        int movieId = Integer.parseInt(grdMovies.getValueAt(iSelectedRow, 0).toString());
        
             
         if (newMovie == null)
            {
                newMovie = new NewMovie(this);
            }
         
        newMovie.iMovieId = movieId; 
        newMovie.sMovieName = grdMovies.getValueAt(iSelectedRow, 1).toString();        
        newMovie.sBanner = grdMovies.getValueAt(iSelectedRow, 2).toString();
        newMovie.sGenere = grdMovies.getValueAt(iSelectedRow, 3).toString();
        newMovie.sReleaseDate = grdMovies.getValueAt(iSelectedRow, 4).toString();
        newMovie.sRentAmount = grdMovies.getValueAt(iSelectedRow, 5).toString();
        newMovie.sTotalCopies = grdMovies.getValueAt(iSelectedRow, 6).toString();
        newMovie.sAvailCopies = grdMovies.getValueAt(iSelectedRow, 7).toString();
        
        newMovie.bNew = false; 
        newMovie.setEditValues();
        newMovie.setVisible(true);
        //this.setVisible(false);  
    }

    private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
        // search
    	
    	List<Movie> movies;
    	
    	if (validateSearchParameters())
    		movies = findMovies();
    	else
    		movies = getAllMovies();
 	    
         loadMovies(movies);
    }
    
    public void loadMovies(List<Movie> movies)
    {
        String movieId, movieName, movieBanner, category, releaseDate, rentAmount, totalCopies, availcopies;
        String[] columns = new String[]{"MovieID", "Movie Name", "Movie Banner", "Category", "Release Date", "Rent Amount", "Total Copies", "Avail Copies"};        
        DefaultTableModel modal = new DefaultTableModel(new String[][]{}, columns);
                   
        if (movies.size() > 0)
        {
                            
            for(int i=0; i< movies.size(); i++)
            {
                Movie movie = movies.get(i);                   
                movieId = String.valueOf(movie.getMovieId());
                movieName = movie.getMovieName();
                movieBanner = movie.getMovieBanner();
                category = movie.getMovieCategory();
                DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
                java.util.Date dt = new java.util.Date(movie.getReleaseDate().getTimeInMillis());
                releaseDate = df.format(dt);                    
                rentAmount = String.valueOf(movie.getRentAmount());
                totalCopies = String.valueOf(movie.getTotalCopies());
                availcopies = String.valueOf(movie.getAvailableCopy());
                
                modal.addRow(new String[]{movieId, movieName, movieBanner, category, releaseDate, rentAmount, totalCopies, availcopies});
            }
        }
                
        grdMovies.setModel(modal);
        
    }
    
    private List<Movie> getAllMovies()
    {
    	try
    	{
    		MovieServiceImplProxy proxy = new MovieServiceImplProxy();
    		MovieResponse response = proxy.getAllMovies();
    		
    		List<Movie> lst = new ArrayList<Movie>();
    		
    		if (response.getMovies() != null)
    			lst = Arrays.asList(response.getMovies());
    		
    		return lst;
    	}
    	catch(Exception ex)
    	{
    		ex.printStackTrace();
    	}
    	
    	return null;
    }
    
    private MovieResponse deletePerson(int movieId)
    {
    	try
    	{
    		Movie movie = new Movie();
    		movie.setMovieId(movieId);
    		
    		MovieServiceImplProxy proxy = new MovieServiceImplProxy();
    		MovieResponse movieResponse = proxy.deleteMovie(movie);    		
    		return movieResponse;
    	}
    	catch(Exception ex)
    	{
    		ex.printStackTrace();
    	}
    	
    	return null;
    }
    
    private List<Movie> findMovies()
    {
    	Movie movie = new Movie();
    	
    	try
    	{
    	   		
    		//Person person = new Person();
    		
    		if (!txtName.getText().equals(""))
    			movie.setMovieName(txtName.getText());
    		
    		if (!txtBanner.getText().equals(""))
    			movie.setMovieBanner(txtBanner.getText());
    		
    		if (!txtCategory.getText().equals("")) 
    			movie.setMovieCategory(txtCategory.getText());
    		
    		if (!txtYear.getText().equals("")){
    			Calendar cal = Calendar.getInstance();
    			cal.set(Integer.parseInt(txtYear.getText()), 01, 01);
    			movie.setReleaseDate(cal);    			
    		}
    		    		    		    		    		    		
    		MovieServiceImplProxy proxy = new MovieServiceImplProxy();
    		MovieResponse response = proxy.findMovie(movie); 
    		Movie[] movies =  response.getMovies();
    		
    		List<Movie> lst = new ArrayList<Movie>();
    		
    		if (movies != null)  		
    			lst = Arrays.asList(movies);
    		    			    	
    		return lst;
    	}
    	catch(Exception ex)
    	{
    		ex.printStackTrace();
    	}
    	
    	return null;
    }
    
    public boolean validateSearchParameters()
    {
    	boolean bResult = true;
    	
    	if (txtBanner.getText().equals("") && txtName.getText().equals("") && txtCategory.getText().equals("") && txtYear.getText().equals(""))
    	{
    		//JOptionPane.showMessageDialog(this, "Please specify atleast one search parameter!");
    		bResult = false;
    	}
    	
    	return bResult;
    }
    
    private MovieResponse issueMovie(int memberID, int movieID)
    {
    	try
    	{
    		Person person = new Person();
    		person.setMemberId(memberID);
    		Movie movie = new Movie();
    		movie.setMovieId(movieID);
    		
    		MovieServiceImplProxy proxy = new MovieServiceImplProxy();
    		MovieResponse movieResponse = proxy.issueMovie(movie, person); 
    		if (movieResponse.getError() == 0)
    		{
    			JOptionPane.showMessageDialog(this, "Movie Issued successfully.");
    		}
    		else
    		{
    			JOptionPane.showMessageDialog(this, movieResponse.getErrorMessage());	
    		}
    		return movieResponse;
    	}
    	catch(Exception ex)
    	{
    		ex.printStackTrace();
    	}
    	
    	return null;
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new AllMovies().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify
    private javax.swing.JTable grdMovies;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButton4;
    private javax.swing.JButton jButton5;
    private javax.swing.JButton jButton6;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextField txtBanner;
    private javax.swing.JTextField txtCategory;
    private javax.swing.JTextField txtName;
    private javax.swing.JTextField txtYear;
    // End of variables declaration
}
